package com.taoz.taozrpc.springboot.starter.bootstrap;

import com.taoz.rpc.core.config.ApplicationConfig;
import com.taoz.rpc.core.registry.Registry;
import com.taoz.rpc.core.registry.RegistryFactory;
import com.taoz.rpc.core.server.tcp.VertxTcpServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

@Slf4j
public class RpcInitBootstrap implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 与注册中心建立连接
        try {
            Registry remoteRegistry = RegistryFactory.getRegistry();
            remoteRegistry.init();
        } catch (Exception e) {
            throw new RuntimeException("未能成功与远程的注册中心建立连接");
        }

        // 是服务器的话，启动监听
        boolean isServer = ApplicationConfig.getConfig().isServer();
        if (isServer) {
            int serverPort = ApplicationConfig.getConfig().getServerPort();
            VertxTcpServer server = new VertxTcpServer();
            server.start(serverPort);
            log.info("Server is listening at port: {}", serverPort);
        }
    }
}
